package qiniufile

import (
	"context"
	"strconv"
	"strings"

	"mall/service/attachment/rpc/attachmentclient"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/utils/pointy"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateFileLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateFileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateFileLogic {
	return &UpdateFileLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateFileLogic) UpdateFile(req *types.UpdateMediaFileReq) (resp *types.BaseMsgResp, err error) {
	var res *attachmentclient.BaseResp
	if len(req.Ids) > 0 {
		var ids []string
		for _, id := range req.Ids {
			ids = append(ids, strconv.FormatInt(int64(id), 10))
		}
		res, err = l.svcCtx.AttachmentRpc.BackendBatchUpdateRecord(l.ctx, &attachmentclient.RecordListReq{
			Diagnose: req.Method,
			Ids:      pointy.GetPointer(strings.Join(ids, ",")),
			Days:     req.Days,
		})
	} else {
		res, err = l.svcCtx.AttachmentRpc.BackendUpdateRecord(l.ctx, &attachmentclient.RecordInfo{
			Id:       req.Id,
			Diagnose: req.Method,
			Bucket:   req.Bucket,
			Key:      req.Key,
			Days:     req.Days,
		})
	}
	if err != nil {
		return nil, err
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
	}, nil
}
